package wps.mojo.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.jdom.JDOMException;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @Author : <a href="mailto:Juanyong.zhang@carefirst.com">Cham
 *         Juanyong.zhang</a>
 * @Date : Apr 14, 2011
 */
public class FreemarkerHelper {
	public static void process(InputStream template, Map<Object, Object> nameValuePairs,
			Writer out) throws IOException, TemplateException,
			DocumentException, JDOMException {
		Configuration cfg = new Configuration();
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		Template temp = new Template(null, new InputStreamReader(template), cfg);
		temp.process(handleFreemarkerDataMappingAfterPopulation(nameValuePairs), out);
		out.flush();
	}

	public static void process(String template, Map<Object, Object> nameValuePairs,
			Writer out) throws IOException, TemplateException,
			DocumentException, JDOMException {
		process(new FileInputStream(template), nameValuePairs, out);

	}

	public static Map<Object, Object> handleFreemarkerDataMappingAfterPopulation(
			Map<Object, Object> nameValuePairs) {
		Map<Object, Object> newNameValuePairs = new HashMap<Object, Object>();

		Set<Object> oldKeys = nameValuePairs.keySet();
		for (Object oldKey : oldKeys) {
			Object value = nameValuePairs.get(oldKey);
			String newKey = StringUtils.replace(oldKey.toString(), ".", "_");
			if (value instanceof String) {
				value = StringHelper.makePrettyIfItsPath((String) value);
			}
			newNameValuePairs.put(newKey, value);
		}

		return newNameValuePairs;
	}
}
